package com.ddd.codegeneration.serviceImpl;

import com.ddd.codegeneration.service.GeneratorBaseCodeService;
import com.ddd.codegeneration.utils.FreeMarkerTemplateUtils;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;

/**
 * @author 官江涛
 * @version 1.0
 * @Title: 基础代码生成
 * @date 2018/7/24/21:55
 */
public class GeneratorBaseCodeServiceImpl implements GeneratorBaseCodeService {



    @Override
    public int generateApi(Map<String, Object> root, String savePath) {
        final String templateName = "/vue/api.ftl";
        final String suffix = ".js";
        final String path = savePath + "api" + suffix;
        generateFileByTemplate(templateName, root, path);
        return 1;
    }


    /**
     * 代码生成器
     * @param templateName  使用的模板名称
     * @param attrs 赋值的参数
     * @param path  生成的路径
     */
    private static void generateFileByTemplate(String templateName, Map<String, Object> attrs, String path){
        File file = new File(path);
        Template template = null;
        try {
            template = FreeMarkerTemplateUtils.getTemplate(templateName);
            FileOutputStream fos = new FileOutputStream(file);
            Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
            template.process(attrs,out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
